package controllers

import (
	"database/sql"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
	"strconv"
	_ "test/mysql"
	"time"
)

/*
*return a json file
 */

func HistoryController(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Access-Control-Allow-Origin", "*")
	w.Header().Add("Access-Control-Allow-Headers", "Content-Type")
	w.Header().Set("content-type", "application/json")
	type Data struct {
		Id            int    `json:uid`
		Ciid          string `json:username`
		Save_time     int    `json:department`
		Tag_value     int    `json:created`
		Tag_dtype     int    `json:created`
		Tag_timestamp int    `json:created`
		Tag_quality   int    `json:created`
		Create_time   string `json:created`
	}
	type Res struct {
		// Total int    `json:total`
		Status int    `json:status`
		Info   string `json:info`
		Msg    []Data `json:product`
	}
	// w.Header().Set("Access-Control-Allow-Origin", "*")
	// w.Header().Add("Access-Control-Allow-Headers", "Content-Type")
	// w.Header().Set("content-type", "application/json")
	if r.Method == "POST" {
		b, err := ioutil.ReadAll(r.Body)
		r.Body.Close()
		if err != nil {
			fmt.Printf("%s", err)
			return
		}
		// fmt.Printf("%s", b)
		var where string = ""
		var xxx = map[string]string{}
		err = json.Unmarshal([]byte(b), &xxx)
		ciid, _ := xxx["ciid"]
		if ciid != "" {
			where = "ciid = \"" + ciid + "\""
		}
		strat_date, _ := xxx["strat_date"]
		end_date, _ := xxx["end_date"]
		// fmt.Printf("%s\n", strat_date)
		// fmt.Printf("%s\n", end_date)
		// fmt.Println(theTime) //打印输出theTime 2015-01-01 15:15:00 +0800 CST
		// fmt.Println(sr)
		if strat_date != "" {
			loc, _ := time.LoadLocation("Local")                                            //重要：获取时区
			theStratTime, _ := time.ParseInLocation("2006-01-02 15:04:05", strat_date, loc) //使用模板在对应时区转化为time.time类型
			strat_time := theStratTime.Unix() - 60*8*60                                     //转化为时间戳 类型是int64
			theEndTime, _ := time.ParseInLocation("2006-01-02 15:04:05", end_date, loc)     //使用模板在对应时区转化为time.time类型
			end_time := theEndTime.Unix() - 60*8*60
			// fmt.Printf("%s\n", strat_time)
			// fmt.Printf("%s\n", end_time)
			if where != "" {
				where = where + " and save_time BETWEEN " + strconv.FormatInt(strat_time, 10) + " AND " + strconv.FormatInt(end_time, 10)
			} else {
				where = " save_time BETWEEN " + strconv.FormatInt(strat_time, 10) + " AND " + strconv.FormatInt(end_time, 10)
			}

		}
		// db, err := sql.Open("mysql", "fy:fy0123498765@tcp(192.168.1.15:3306)/imhdb?charset=utf8")
		db, err := sql.Open("mysql", "fy:fy0123498765@tcp(127.0.0.1:3306)/imhdb?charset=utf8")
		checkErr(err)
		// db, err := sql.Open("mysql", "fy:fy0123498765@tcp(localhost:3306)/imhdb?charset=utf8")
		// query, _ := db.Query("SELECT * FROM t_go_history WHERE ciid = " + id + " and save_time BETWEEN " + strat_time + " AND " + end_time)
		query, _ := db.Query("SELECT * FROM t_history WHERE " + where)

		column, _ := query.Columns()
		values := make([][]byte, len(column))     //values是每个列的值，这里获取到byte里
		scans := make([]interface{}, len(column)) //因为每次查询出来的列是不定长的，用len(column)定住当次查询的长度
		for i := range values {                   //让每一行数据都填充到[][]byte里面
			scans[i] = &values[i]
		}
		var m Res
		m.Status = 0
		m.Info = "ok"
		fmt.Println(scans)
		for query.Next() { //循环，让游标往下移动
			var id int
			var ciid string
			var save_time int
			var tag_value int
			var tag_dtype int
			var tag_timestamp int
			var tag_quality int
			var create_time string
			if err := query.Scan(scans...); err != nil { //query.Scan查询出来的不定长值放到scans[i] = &values[i],也就是每行都放在values里
				fmt.Println(err)
				return
			}
			err = query.Scan(&id, &ciid, &save_time, &tag_value, &tag_dtype, &tag_timestamp, &tag_quality, &create_time)
			checkErr(err)
			orderi := Data{Id: id, Ciid: ciid, Save_time: save_time, Tag_value: tag_value, Tag_dtype: tag_dtype, Tag_timestamp: tag_timestamp, Tag_quality: tag_quality, Create_time: create_time}
			m.Msg = append(m.Msg, orderi)
		}
		db.Close()
		bytes, _ := json.Marshal(m)
		w.WriteHeader(http.StatusOK)
		w.Write(bytes)
	}

}

// func checkErr(err error) {
// 	if err != nil {
// 		panic(err)
// 	}
// }
